package yushuman.rbac.view;

import yushuman.rbac.domain.vo.BaseVo;
import yushuman.rbac.domain.vo.Result;
import yushuman.rbac.service.IBaseService;

/**
 * 视图层-基类
 *
 * @author 俞舒熳
 * @since 2025/6/6 10:50
 */
public abstract class BaseView<Vo extends BaseVo, IService extends IBaseService> {

    IService service;

    Vo[] cache;

    void printError(String message) {
        System.out.println("\033[31m" + message + "\033[0m");
    }

    Vo getCacheById() {
        System.out.print("请输⼊ID，ID必须是⼤于0的整数：");

        if (!MainView.input.hasNextInt()) {
            MainView.input.nextLine();
            System.out.println("ID必须为整数，请输⼊整数值");
            return null;
        }
        int id = MainView.input.nextInt();
        MainView.input.nextLine();

        if (id < 1) {
            System.out.println("ID必须⼤于0，请重新输⼊");
            return null;
        }

        if (cache == null) {
            Result result = service.list();
            cache = (Vo[]) result.data;
        }

        Vo vo = null;
        for (Vo item : cache) {
            if (item.id == id) {
                System.out.println("该ID对应的数据是：");
                System.out.println(item);
                vo = item;
                break;
            }
        }
        if (vo == null) {
            printError("当前没有该ID对应的数据");
            return null;
        }

        return vo;
    }
}
